package com.itqf.dao.impl;

import com.itqf.dao.AddressDao;
import com.itqf.entity.Address;
import com.itqf.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {

    //初始化工具类对象
    private static QueryRunner queryRunner = new QueryRunner();


    @Override
    public List<Address> selectAddressByUid(int uid) throws SQLException {
        //编写sql语句
        String sql = "select a_id as aid, u_id as uid,a_name as aname,a_phone " +
                "as aphone,a_detail as adetail ,a_state as astate from " +
                "address where u_id = ? order by a_state desc;";

        List<Address> list = queryRunner.query(DbUtils.getConnection(), sql, new BeanListHandler<Address>(Address.class), uid);

        return list;
    }

    @Override
    public void insertAddress(Address address) throws SQLException {
        String sql = "insert into address (u_id,a_name,a_phone,a_detail,a_state) value(?,?,?,?,?)";

        //设置参数列表
        Object[] obj = {address.getUid(),address.getAname(),address.getAphone(),address.getAdetail(),address.getAstate()};

        queryRunner.update(DbUtils.getConnection(),sql,obj);
    }

    @Override
    public void deleteAddressByAid(String aid) throws SQLException {
        String sql = "delete from address where a_id=?";

        queryRunner.update(DbUtils.getConnection(),sql,aid);
    }

    @Override
    public void updateAddressToDefult(String aid) throws SQLException {
        String sql = "update address set a_state = 1 where a_id = ?";

        queryRunner.update(DbUtils.getConnection(),sql,aid);
    }

    @Override
    public void updateAddressToCommons(String aid, int uid) throws SQLException {
        String sql = "update address set a_state = 0 where a_id != ? and u_id = ?";

        queryRunner.update(DbUtils.getConnection(),sql,aid,uid);
    }

    @Override
    public void updateAddressByAid(Address address) throws SQLException {

        String sql = "update address set a_state = ?,a_name=?,a_phone=?,a_detail = ? where a_id = ?;";
        Object[] obj = {address.getAstate(),address.getAname(),address.getAphone(),address.getAdetail(),address.getAid()};

        queryRunner.update(DbUtils.getConnection(),sql,obj);
    }


}
